#include <linux/init.h>
#include <linux/module.h>
#include <net/sock.h>
#include <net/netlink.h> 

#define NETLINK_TEST 25
#define MAX_PAYLOAD_SIZE 1024

struct sock *nl_sk = NULL;

void sendnlmsg(int pid)
{
    struct sk_buff *skb;
    struct nlmsghdr *nlh;

    char msg[30] = "Say hello from kernel!";

    if(!nl_sk){
        return;
    }

    skb = nlmsg_new(MAX_PAYLOAD_SIZE, GFP_KERNEL);
    if(!skb){
        printk(KERN_ERR "nlmsg_new error!\n");
    }
    nlh = nlmsg_put(skb, 0, 0, 0, MAX_PAYLOAD_SIZE, 0);

    memcpy(NLMSG_DATA(nlh), msg, sizeof(msg));
    printk("Send message '%s'.\n",(char *)NLMSG_DATA(nlh));

    netlink_unicast(nl_sk, skb, pid, MSG_DONTWAIT);
}

void nl_data_ready(struct sk_buff *__skb)
{
    struct sk_buff *skb;
    struct nlmsghdr *nlh;
    char str[100];
	
    skb = skb_get (__skb);
    if(skb->len >= NLMSG_SPACE(0)){
        nlh = nlmsg_hdr(skb);

        memcpy(str, NLMSG_DATA(nlh), sizeof(str));
        printk("Message received:%s\n",str) ;
        sendnlmsg(nlh->nlmsg_pid);
        kfree_skb(skb);
    }
}

static int netlink_unicast_init(void)
{
    struct netlink_kernel_cfg netlink_kerncfg = {
        .input = nl_data_ready,
    };
    nl_sk = netlink_kernel_create(&init_net, NETLINK_TEST, &netlink_kerncfg);

    if(!nl_sk){
        printk(KERN_ERR "netlink_unicast_init: Create netlink socket error.\n");
        return -1;
    }

    printk("netlink_unicast_init: Create netlink socket ok.\n");
    return 0;
}

static void netlink_unicast_exit(void)
{
    if(nl_sk != NULL){
        sock_release(nl_sk->sk_socket);
    }

    printk("netlink_unicast_exit!\n");
}

module_init(netlink_unicast_init);
module_exit(netlink_unicast_exit);

MODULE_AUTHOR("X-SLAM XINU");
MODULE_LICENSE("GPL");

